package org.footearth.util;

import java.util.Map;

import javax.servlet.http.HttpServlet;

import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

public class JettyServer {

	public static boolean startServer(int Port, String ContextPath,
			Map<HttpServlet, String> Servlet) {

		boolean retCode = false;

		Server server = new Server();
		ServerConnector connector = new ServerConnector(server);
		connector.setPort(Port);

		server.setConnectors(new Connector[] { connector });

		ServletContextHandler context = new ServletContextHandler(
				ServletContextHandler.SESSIONS);
		// ServletContextHandler context = new ServletContextHandler();
		HandlerCollection handlers = new HandlerCollection();
		handlers.setHandlers(new Handler[] { context, new DefaultHandler() });
		server.setHandler(handlers);

		context.setContextPath(ContextPath);

		// servlet mapping Start

		for (Map.Entry<HttpServlet, String> entry : Servlet.entrySet()) {
			HttpServlet CurServlet = entry.getKey();
			String CurPath = entry.getValue();
			context.addServlet(new ServletHolder(CurServlet), CurPath);
		}

		try {
			server.start();
			server.join();
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}

		retCode = true;
		return retCode;
	}
}
